package com.deltabravomedia.theoldtoad;

import java.io.File;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class DrinksBeersGuest extends ListActivity {
	private static final int ACTIVITY_ALES=0;
	private static final int ACTIVITY_DRAUGHTS=1;
	private static final int ACTIVITY_IMAGE=2;
	
	private static final String TAG = "DrinksBeersGuest";

	private ProgressDialog m_ProgressDialog = null; 
    private ArrayList<Item> m_items = null;
    private ItemAdapter m_adapter;
    private Runnable viewItems;
    private Runnable getFiles;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listviewwithbackgroundimage);
        this.setTitle("The Old Toad : Drinks : Beers : Guest");
        m_items = new ArrayList<Item>();
        this.m_adapter = new ItemAdapter(this, R.layout.rowheader, m_items);
                setListAdapter(this.m_adapter);
        
        viewItems = new Runnable(){
            @Override
            public void run() {
                getItems();
            }
        };
        
        Thread thread =  new Thread(null, viewItems, "MagentoBackground");
        thread.start();
        m_ProgressDialog = ProgressDialog.show(DrinksBeersGuest.this,    
              "Please wait...", "Retrieving data ...", true);
    }
    
	@Override
    protected void onListItemClick (ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
         
        String item = m_items.get(position).getClassName();

        if (item != null) {
            if (item.equals("DrinksBeersGuestAles")) {
                Intent i = new Intent(this, ItemsList.class);
                i.putExtra("title", "Drinks : Beer : Guest : Ales");
                i.putExtra("type", "GuestAles");
                startActivityForResult(i, ACTIVITY_ALES);
            } else if (item.equals("DrinksBeersGuestDraughts")) {
                Intent i = new Intent(this, ItemsList.class);
                i.putExtra("title", "Drinks : Beer : Guest : Draughts");
                i.putExtra("type", "GuestDraughts");            
                startActivityForResult(i, ACTIVITY_DRAUGHTS);
            }        	
        }
        else {
            String fileName = m_items.get(position).getItemName().replaceAll("\\W", "").trim();
            fileName = this.getFilesDir() + "/" + fileName;
    
            File file = new File(fileName);
            if (file.length() > 0) {
            	Intent i = new Intent(this, Image.class);
            	i.putExtra("fileName", fileName);
            	i.putExtra("title", "The Old Toad : Beers : Guest : " + m_items.get(position).getItemName());
            	startActivityForResult(i, ACTIVITY_IMAGE);
            } else {
            	Log.w(TAG, "No image file: " + fileName);
            }
        }
	}   
    
    private Runnable returnRes = new Runnable() {
        @Override
        public void run() {
            if(m_items != null && m_items.size() > 0){
                m_adapter.notifyDataSetChanged();
                for(int i=0;i<m_items.size();i++)
                m_adapter.add(m_items.get(i));
            }
            m_ProgressDialog.dismiss();
            m_adapter.notifyDataSetChanged();
        }
    };
    
    private class ItemAdapter extends ArrayAdapter<Item> {

        private ArrayList<Item> items;

        public ItemAdapter(Context context, int textViewResourceId, ArrayList<Item> items) {
	        super(context, textViewResourceId, items);
	        this.items = items;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			if (view == null) {
			    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			    view = vi.inflate(R.layout.rowheader, null);
			}
			Item item = items.get(position);
			if (item != null) {
		        TextView topText = (TextView) view.findViewById(R.id.toptext);
		        if (topText != null) {
		        	if (item.getHeaderName() != null) {
			        	if (item.getHeaderName().trim().equals("")) {
				    		topText.setLines(0);				        		
			        	} else {
				    		topText.setSingleLine(false);
				    		topText.setText(item.getHeaderName());
		        		}
		        	} else {
			    		topText.setLines(0);				        				        		
		        	}
		        }
		        
		        TextView nameText = (TextView) view.findViewById(R.id.nametext);
		        if (nameText != null) {
		        	if (item.getItemName() != null) {
			        	if (item.getItemName().trim().equals("")) {
				    		nameText.setLines(0);				        		
			        	} else {
				    		nameText.setSingleLine(false);
		        			nameText.setText(item.getItemName());
		        		}
		        	} else {
			    		nameText.setLines(0);				        				        		
		        	}
		        }

		        TextView costText = (TextView) view.findViewById(R.id.costtext);
		        if (costText != null) {
		        	if (item.getCost() != null) {
			        	if (item.getCost().trim().equals("")) {
				    		costText.setLines(0);				        		
			        	} else {
				    		costText.setSingleLine(false);
		        			costText.setText(item.getCost());
		        		}
		        	} else {
			    		costText.setLines(0);				        				        		
		        	}
		        }

		        TextView descriptionText = (TextView) view.findViewById(R.id.descriptiontext);
		        if (descriptionText != null) {
		        	if (item.getDescription() != null) {
			        	if (item.getDescription().trim().equals("")) {
			        		descriptionText.setLines(0);				        		
			        	} else {
				    		descriptionText.setSingleLine(false);
			        		descriptionText.setText(item.getDescription());
		        		}
		        	} else {
			    		descriptionText.setLines(0);				        				        		
		        	}
		        }  

		        TextView recommendText = (TextView) view.findViewById(R.id.recommendtext);
		        if (recommendText != null) {
		        	if (item.getRecommend() != null) {
			        	if (item.getRecommend().trim().equals("")) {
			        		recommendText.setLines(0);				        		
			        	} else {
				    		recommendText.setSingleLine(false);
			        		recommendText.setText(item.getRecommend());
		        		}
		        	} else {
			    		recommendText.setLines(0);				        				        		
		        	}
		        }
			}
			return view;
        }
    }
    
    private void getItems(){
		m_items = new ArrayList<Item>();
		
		Item item0 = new Item();
		item0.setHeaderName("Guest Ales");
		item0.setIconName("ales");
		item0.setClassName("DrinksBeersGuestAles");
		m_items.add(item0);
		addItems(item0.getClassName());
		
		Item item1 = new Item();
		item1.setHeaderName("Guest Draughts");
		item1.setIconName("draughts");
		item1.setClassName("DrinksBeersGuestDraughts");
		m_items.add(item1);
		addItems(item1.getClassName());
		
		Log.i("ARRAY", ""+ m_items.size());
		  
		runOnUiThread(returnRes);
    }
    
	private void addItems(String type) {
		type = type.replaceFirst("DrinksBeers", "");
		
		String jsonString = Utilities.getJsonString(type, Utilities.GET_ITEM_URL + type, this);

    	JSONObject json;
		try {
			json = new JSONObject(jsonString);
        
	        if (json.has(type)) {
	        	JSONArray starters = json.getJSONArray(type);

	        	for (int i = 0; i < starters.length(); i++ ){
	        		JSONObject jsonStarter = starters.getJSONObject(i);
	        		Item item = new Item();

	        		item.setItemName(jsonStarter.getString("name"));
	        		item.setCost(jsonStarter.getString("cost"));
	        		item.setDescription(jsonStarter.getString("description"));
	        		item.setRecommend(jsonStarter.getString("recommend"));

	        		if (Utilities.wasUpdated) {
	        			final String fileName = jsonStarter.getString("name").trim()
        				.replaceAll("\\W", "");
	        			
	        	        getFiles = new Runnable(){
	        	            @Override
	        	            public void run() {
	        	            	getFile(fileName);	
	        	            }
	        	        };
	        	        
	        	        Thread thread =  new Thread(null, getFiles, "MagentoBackground");
	        	        thread.start();	
	        		}
	        		
	        		m_items.add(item);	        		
	        	}
	        }
		} catch (JSONException e) {
			Log.w(TAG, e.getMessage());
		}
        
		Log.i("ARRAY", ""+ m_items.size());
	}
	
	protected void getFile(String fileName) {
		Utilities.getFileFromServer(fileName, this);
	}
}